const express = require('express')
const router = express.Router()
const path = require('path')
const sha1 = require('sha1')
const UserModel = require('../modles/user')
router.get('/', function (req, res) {
    res.render('siginup', {
        title: '用户注册'
        , layout: 'layout'
    })
})
router.post('/', (req, res) => {
    const name = req.fields.name
    const gender = req.fields.gender
    const bio = req.fields.bio
    let password = req.fields.password
    const avatar = req.files.avatar.path.split(path.sep).pop()

    // 明文密码加密
    password = sha1(password)

    // 待写入数据库的用户信息
    let user = {
        name: name,
        password: password,
        gender: gender,
        bio: bio,
        avatar: avatar
    }
    // 用户信息写入数据库
    UserModel.create(user).then(function (result) {
        user = result.ops[0]
        console.log(user)
        req.session.user = user
        // 写入 flash
        req.flash('success', '注册成功')
        // 跳转到首页
        res.redirect('/main')
    })
});

module.exports = router